<?php
declare (strict_types=1);

namespace app\common\service;

use app\admin\logic\system\Config as SystemConfig;
use app\common\command\decrypt\Des;
use app\common\exception\LogicException;
use app\common\logic\Payment as PaymentLogic;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use think\Request;
use think\Response;

/**
 * 支付接口类
 */
class Payment extends BaseService
{

    /**
     * 支付页面 - 支付方式请求
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-05-06
     */
    public function orderPayFetch(): Response
    {
        $payway = app(PaymentLogic::class)->orderPayFetch();

        return static::parseToData($payway, 1, '获取成功');
    }

    /**
     * 支付页面 - 去支付
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-05-06
     */
    public function orderPayCreate(Request $request): Response
    {
        $param = $request->post();
        $re    = app(PaymentLogic::class)->doPay($param);
        // return app(POI::class)->where('ext_data->getway', 1)->select();
        if ($param['pay_type'] != 'lcnpay') {
            return static::parseToData(['paybody' => $re], 1, '获取成功');
        }
        return static::parseToData($re, 1, '支付成功');
    }

    /**
     * 查询订单
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-05-06
     *
     * @param Request $request
     * @return Response
     */
    public function orderquery(Request $request): Response
    {
        $param = $request->get();
        $re    = app(PaymentLogic::class)->orderquery($param);

        return static::parseToData($re, 1, '获取成功');
    }

    /**
     * 微信公众号appid
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/01/16
     *
     * @return Response
     */
    public function getWxAppId(): Response
    {
        $conf = SystemConfig::get('system.config.official', ['appid' => ''], request()->mhm_id);

        return static::parseToData($conf['appid'], 1, '获取成功');
    }

    /**
     * 获取微信用户openid
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-30
     */
    public function getWxUserOpenid(Request $request): Response
    {
        $h5   = request()->device_type == 'h5';
        $conf = $h5 ? SystemConfig::get('system.config.official', [], request()->mhm_id) : SystemConfig::get('system.login.miniapp', [], request()->mhm_id);

        $appid  = $conf['appid'];
        $secret = $conf['secret'];
        $param  = $request->get();
        $code   = $param['code'] ?? '';
        $params = [
            'appid'      => $appid,
            'secret'     => $secret,
            'grant_type' => 'authorization_code',
        ];
        if ($h5) {
            $params['code'] = $code;
            $url            = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        } else {
            $params['js_code'] = $code;
            $url               = 'https://api.weixin.qq.com/sns/jscode2session?';
        }
        $url .= http_build_query($params);
        try {
            $client   = new Client();
            $res      = $client->request('get', $url);
            $response = $res->getBody()->getContents();
            $response = json_decode($response);
            // Db::name('test')->save(['msg' => 'get miniapp openid response:' . $response]);
            if (isset($response->errcode)) throw new LogicException('微信配置错误，请联系商家', $response->errmsg);
            $openid = $response->openid ?? '';

        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                throw new LogicException('微信配置错误，请联系商家', $e->getResponse());
            }
            throw new LogicException('微信配置错误，请联系商家', $e->getRequest());
        } catch (Exception $e) {
            throw new LogicException($e->getMessage());
        }
        $desOpenid = Des::jiami($openid);
        return static::parseToData($desOpenid, 1, 'success');
    }
}
